#picaxe 18m2
#terminal 4800
;
; The HD44780 is driven from a PCF8574 8 Bit I/O expander for i2c-bus
;
	SYMBOL PCF8574_ADDR = $40
	SYMBOL PCF8574_HD44780_RS = %00000001
	SYMBOL PCF8574_HD44780_RW = %00000010
	SYMBOL PCF8574_HD44780_E  = %00000100
	SYMBOL PCF8574_HD44780_BL = %00001000
;
; Runtime Data
;
;	M2 parts have b0-b27 mapped onto w0-w13
;
	SYMBOL HD44780BYTE = B0
	SYMBOL HD44780NIBBLE = B1
	SYMBOL TMP = B2
	SYMBOL PCF8574BYTE = B5
	SYMBOL STRPTR = B9
;
; Static EEPROM data
;
	SYMBOL EEHELLOWORLD = 0
	EEPROM EEHELLOWORLD,("Hello, World",0)
	;
	ENABLETIME		
;
; Setup the I2C bus for the PCF8574.
;
	I2CSLAVE PCF8574_ADDR, I2CSLOW, I2CBYTE
	
	GOSUB HD44780INIT
;
;	Display our title
;
	STRPTR = EEHELLOWORLD
	GOSUB PRINTSTRING
;
MAIN:	
	GOTO MAIN
;
; Print String
;
PRINTSTRING:
	READ STRPTR,HD44780BYTE
	DO
	    GOSUB HD44780WRITEDATABYTE
	    STRPTR = STRPTR + 1
	    READ STRPTR,HD44780BYTE
	LOOP WHILE HD44780BYTE <> 0
	RETURN	
;
;	HD44780 Init
;
;
; HD44780 - HD44780INIT
;
HD44780INIT:	
	HD44780BYTE = $33			;Function set (4-bit interface, 1 line, 5*7 Pixels) 
	GOSUB	HD44780WRITECOMMANDBYTE
	
	HD44780BYTE = $32			;Function set (4-bit interface, 1 line, 5*7 Pixels) 
	GOSUB	HD44780WRITECOMMANDBYTE

	HD44780BYTE = $28			;Function set (4-bit interface, 2 lines, 5*7 Pixels) 
	GOSUB	HD44780WRITECOMMANDBYTE
	
	HD44780BYTE = $0C			;Entry Mode 6 
	GOSUB	HD44780WRITECOMMANDBYTE
	
	HD44780BYTE = $01			;Clear Screen
	GOSUB	HD44780WRITECOMMANDBYTE
	
	RETURN
;
; HD44780 - HD44780CLR
;
HD44780CLR:
	HD44780BYTE = $01				;Clear Screen
	GOSUB	HD44780WRITECOMMANDBYTE
	RETURN	
;	
; HD44780 - HD44780LINE2
;
HD44780LINE2:
	HD44780BYTE = $80 + $40			;Move to start of line 2 
	GOSUB	HD44780WRITECOMMANDBYTE	
	RETURN		
;
; PCF8574 - HD44780 - WRITE COMMAND BYTE
;		
HD44780WRITECOMMANDBYTE:
	PCF8574BYTE = HD44780BYTE & $F0
	GOSUB PCF8574WRITEBYTE
	PCF8574BYTE = HD44780BYTE & $0F
	PCF8574BYTE = PCF8574BYTE * 16
	GOSUB PCF8574WRITEBYTE						
	RETURN	
;
; PCF8574 - HD44780 - WRITE DATA BYTE
;	
HD44780WRITEDATABYTE:
	PCF8574BYTE = HD44780BYTE & $F0
	PCF8574BYTE = PCF8574BYTE | PCF8574_HD44780_RS
	GOSUB PCF8574WRITEBYTE
	PCF8574BYTE = HD44780BYTE & $0F
	PCF8574BYTE = PCF8574BYTE * 16
	PCF8574BYTE = PCF8574BYTE | PCF8574_HD44780_RS 
	GOSUB PCF8574WRITEBYTE						
	RETURN					;Done
;	
; HD44780 - WRITE NIBBLE
;
PCF8574WRITEBYTE:
	TMP = PCF8574BYTE | PCF8574_HD44780_E | PCF8574_HD44780_BL	
							;Set the Enable pin high
	WRITEI2C (TMP)				;Write it out
	PAUSE 1					;Wait
	TMP = TMP XOR PCF8574_HD44780_E	;Clear the Enable pin
	WRITEI2C (TMP)				;Write it out again
	RETURN

	END